package com.gitlab.techschool.pcbook.serializer;

import com.gitlab.techschool.pcbook.pb.Laptop;
import com.google.protobuf.util.JsonFormat;

import java.io.*;

public class Serializer {

    public void writeBinaryFile(Laptop laptop, String filename) throws IOException {
        FileOutputStream outStream = new FileOutputStream(filename);
        laptop.writeTo(outStream);
        outStream.close();
    }

    public Laptop readBinaryFile(String filename) throws IOException {
        FileInputStream inStream = new FileInputStream(filename);
        Laptop laptop = Laptop.parseFrom(inStream);
        inStream.close();
        return laptop;
    }

    public void writeJSONFile(Laptop laptop, String filename) throws IOException {
        JsonFormat.Printer printer = JsonFormat.printer()
                .includingDefaultValueFields()
                .preservingProtoFieldNames();
        String json = printer.print(laptop);
        FileOutputStream outStream = new FileOutputStream(filename);
        outStream.write(json.getBytes());
        outStream.close();
    }

    public Laptop readJSONFile(String filename) throws IOException {
        FileReader reader = new FileReader(filename);
        Laptop.Builder builder = Laptop.newBuilder();
        JsonFormat.parser().merge(reader, builder);
        Laptop laptop = builder.build();
        reader.close();
        return laptop;
    }
}
